package com.qupai.controller.user;

import com.qupai.constant.JwtClaimsConstant;
import com.qupai.dto.UserDTO;
import com.qupai.dto.UserLoginDTO;
import com.qupai.entity.User;
import com.qupai.properties.JwtProperties;
import com.qupai.result.Result;
import com.qupai.service.UserService;
import com.qupai.utils.JwtUtil;
import com.qupai.vo.UserLoginVO;
import com.qupai.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Tag(name = "C端-用户相关接口")
@Slf4j
@RequiredArgsConstructor
public class UserController {


    private final UserService userService;
    private final JwtProperties jwtProperties;

    @Operation(summary = "微信登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("微信用户登录:{}",userLoginDTO.getCode());

        //微信登录
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        Map<String, Object>claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        System.out.println("token:"+token);
        UserLoginVO userLoginVO=UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @GetMapping("/list")
    @Operation(summary = "查询用户信息回显")
    public Result<UserVO> list(){
        log.info("正在查询用户信息");
        UserVO userVO = userService.userlist();
        return Result.success(userVO);
    }

    @PutMapping
    @Operation(summary = "修改用户信息")
    public Result<String> update(@RequestBody UserDTO userDTO){
        log.info("修改用户信息:{}",userDTO);
        userService.update(userDTO);
        return Result.success();
    }

}
